package com.jy.study;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;

import java.util.List;

/**
 * @Classname ArrayUtilsTest
 * @Description 返还一个指定长度的数组
 * @Date 2019/9/30 14:38
 * @Created by  jiaoyong
 */
public class ArrayUtilsTest {

    /**
     * Question：
     * 现有两个数组 A{“a1”,“a2”,“a3”…}、B{“b1”,“b2”,“b3”…}；
     * 按照a1,a2,b1,a3,a4,b2…的序列，返回一个***给定的长度n***的数组
     *
     * @param args
     */
    public static void main(String[] args) {

        String[] str1 = {"a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10"};
        String[] str2 = {"b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "b10"};
        String[] strings = backArray(str1, str2, 13);
        System.out.println("strings = " + strings);
    }

    private static String[] backArray(String[] str1, String[] str2, int n) {
        int a = 1;
        int b = 0;
        List<String> list = CollUtil.newArrayList();
        //根据str1的长度，判定这个长度里面有多少个奇数
        for (int i = 0; i < str1.length; i++) {
            if (i % 2 != 0) {
                b = b + 1;
            }
        }
        //所给定的n一定是小于等于str1的长度与奇数个数之和
        if (n <= str1.length + b) {
            //集合的长度一定与n相等
            for (int i = 0; list.size() < n; i++) {
                //无论i是奇数还是偶数，str1的元素都得加入集合
                list.add(str1[i]);
                if (i % 2 != 0 && list.size() < n) {
                    list.add(str2[i - a]);
                    a++;
                }
            }
        }else {
            System.out.println("给定的长度n不合法，请重新输入！");
        }
        String[] strings = ArrayUtil.toArray(list, String.class);
        System.out.println("strings = " + strings);
        return strings;
    }

}
